package src.main.lagou.pt.week2homework;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;
import java.util.Scanner;

public class BClass {

    public static void main(String[] args) {

        ServerSocket ss = null;
        Socket s = null;
        InputStream in = null;
        ByteArrayOutputStream out = null;

        try {
            // 1.创建ServerSocket类型的对象并提供端口号
            ss = new ServerSocket(8885);

            // 2.等待客户端的连接请求，调用accept方法
            System.out.println("等待客户端的连接请求...");

            // 当没有客户端连接时，则服务器阻塞在accept方法的调用这里
            s = ss.accept();
            System.out.println("客户端 " + s.getInetAddress() + "连接成功！");

            byte[] buf = new byte[1024];

            int lenght = 0;

            in = s.getInputStream();

            out = new ByteArrayOutputStream();

            while ((lenght = in.read(buf)) != -1) {
                out.write(buf, 0, lenght);
            }

            sort(out.toByteArray());

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } finally {
            // 3.关闭Socket并释放有关的资源
            if (null != ss) {
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void sort(byte[] arr) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {

        Class<?> aClass = new MyClassLoader().defineClass(arr);

        int [] array = {4, 3, 65, 34, 55, 23};

        Method method = aClass.getMethod("insertSort", int[].class);

        int[] invoke = (int[]) method.invoke(new MyClassLoader(), array);

        System.out.println(Arrays.toString(invoke));

    }


}
